package com.example.aicodehelper.AI;


import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;

import java.util.Arrays;
import java.util.List;

@Service
public class AiCodeHelperServiceImpl {

    @Resource
    private AiCodeHelperService aiCodeHelperService;

    //    流式处理
    public Flux<String> streamChat(String userMessage) {

        return Flux.<String>create(fluxSink -> {
            try {
                String fullResponse = aiCodeHelperService.chat(userMessage);

                String[] chunks = splitIntoChunks(fullResponse);
                for (String chunk : chunks) {
                    if (fluxSink.isCancelled()) {
                        break;
                    }
                    if (!chunk.trim().isEmpty()) {
                        fluxSink.next(chunk);
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        if (!fluxSink.isCancelled()) {
                            fluxSink.error(e);
                        }
                        return;
                    }
                }
//                完成流
                if (!fluxSink.isCancelled()) {
                    fluxSink.complete();
                }
            } catch (Exception e) {
                if (!fluxSink.isCancelled()) {
                    fluxSink.error(new RuntimeException("AI服务调用失败: " + e.getMessage(), e));
                }
            }
        }).subscribeOn(Schedulers.boundedElastic());    // 在弹性线程池中执行，避免阻塞

    }


    // 改进的文本拆分方法 - 按句子拆分保持语义完整性
    private String[] splitIntoChunks(String text) {
        if (text == null || text.trim().isEmpty()) {
            return new String[]{"AI暂无响应"};
        }

        // 按句子分隔符拆分，保持语义完整性
        String[] sentences = text.split("(?<=[.!?。！？])|(?=\\n)");

        // 过滤空字符串并trim
        return Arrays.stream(sentences)
                .filter(sentence -> !sentence.trim().isEmpty())
                .map(String::trim)
                .toArray(String[]::new);
    }


}
